#include "../Event.h"

#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/locks.hpp>

namespace AlgoTrading
{
	namespace Common
	{

		namespace Impl
		{
			class AutoResetEvent : public AlgoTrading::Common::Event
			{
			public:
				AutoResetEvent(bool initialState)
				{
					eventIsSet = initialState;
				}

				virtual ~AutoResetEvent()
				{
				}

				virtual void Set()
				{
					{
						boost::lock_guard<boost::mutex> lock(mutex);
						eventIsSet = true;
					}
					cond.notify_one();
				}

				virtual void Wait()
				{
					boost::unique_lock<boost::mutex> lock(mutex);
					while(!eventIsSet)
					{
						cond.wait(lock);
					}
					eventIsSet = false;
				}

				virtual bool Wait(int ms)
				{
					boost::unique_lock<boost::mutex> lock(mutex);
					while(!eventIsSet)
					{
						if (!cond.timed_wait(lock, boost::posix_time::milliseconds(ms)))
						{
							return false;
						}
					}
					eventIsSet = false;
					return true;
				}

				virtual void Reset()
				{
					//TODO: implement
				}

			private:
				boost::mutex mutex;
				boost::condition_variable cond;
				bool eventIsSet;
			};
		}

		Event::~Event()
		{
		}

		Event* CreateAutoResetEvent(bool initialState)
		{
			return new AlgoTrading::Common::Impl::AutoResetEvent(initialState);
		}

	}
}